package com.dingreading.cloud.subject.controller;

import com.alibaba.fastjson.JSONArray;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.common.util.aliyun.OSSClientUtil;
import com.dingreading.cloud.common.util.qyweixin.AccessTokenDto;
import com.dingreading.cloud.common.util.qyweixin.QyWeiXinUtil;
import com.dingreading.cloud.common.util.qyweixin.QyWeixinMsg;
import com.dingreading.cloud.subject.dto.SubjectLessonDto;
import com.dingreading.cloud.subject.dto.SubjectLessonIssueDto;
import com.dingreading.cloud.subject.entity.SubjectLessonIssue;
import com.dingreading.cloud.subject.entity.SubjectLessonIssueImg;
import com.dingreading.cloud.subject.entity.Subjects;
import com.dingreading.cloud.subject.service.SubjectLessonIssueImgService;
import com.dingreading.cloud.subject.service.SubjectLessonIssueService;
import com.dingreading.cloud.subject.service.SubjectLessonService;
import com.dingreading.cloud.subject.service.SubjectsService;
import com.dingreading.cloud.subject.util.redis.RedisService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RefreshScope
@RestController
@RequestMapping("/front/subjectLessonIssue")
@Api(tags = "门店-活动课次建议管理")
public class FrontSubjectLessonIssueController {

    @Value("${serverUrl}")
    public String serverUrl;
    @Value("${qyweixin.corpid}")
    public String corpid;
    @Value("${qyweixin.secret}")
    public String secret;
    @Value("${qyweixin.lessonchatid}")
    public String lessonchatid;

    @Resource
    private SubjectLessonIssueService subjectLessonIssueService;
    @Resource
    private SubjectLessonIssueImgService subjectLessonIssueImgService;
    @Resource
    private SubjectLessonService subjectLessonService;
    @Resource
    private SubjectsService subjectsService;
    @Resource
    private RedisService redisService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName
    ) {
        Page<SubjectLessonIssueDto> page = subjectLessonIssueService.pageList(
                pageUtil, storeUid, staffUid, null, null, null, null, null
        );

        List<SubjectLessonIssueDto> list = page.getRecords();
        // 获取图片集合
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> uids = list.stream().map(SubjectLessonIssueDto::getUid).collect(Collectors.toList());
            List<SubjectLessonIssueImg> imgList = subjectLessonIssueImgService.getImgList(uids);
            if (CollectionUtils.isNotEmpty(imgList)) {
                Map<String, List<SubjectLessonIssueImg>> map = imgList.stream()
                        .collect(Collectors.groupingBy(SubjectLessonIssueImg::getIssueUid, LinkedHashMap::new, Collectors.toList()));
                if (!map.isEmpty()) {
                    for (SubjectLessonIssueDto issue : list) {
                        issue.setImgList(map.get(issue.getUid()));
                    }
                }
            }
        }

        long totalRow = page.getTotalRow();
        PageBeanDto dto = new PageBeanDto();
        dto.setTotal(totalRow);
        dto.setList(list);

        return R.ok(dto);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "新增建议")
    @PostMapping(value = "/newBean")
    public R<Object> newBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "课次uid") @RequestParam(value = "lessonUid") String lessonUid,
            @ApiParam(value = "建议内容") @RequestParam(value = "issueContent") String issueContent,
            @ApiParam(value = "联系号码") @RequestParam(value = "mob", required = false) String mob,
            @ApiParam(value = "图片集合json ['','']") @RequestParam(value = "urls", required = false) String urls
    ) throws Exception {
        if (StringUtils.isBlank(issueContent))
            return R.fail("请填写建议内容");

        List<String> urlList = null;
        if (StringUtils.isNotBlank(urls)) {
            urlList = JSONArray.parseArray(urls, String.class);
            if (CollectionUtils.isEmpty(urlList)) {
                return R.fail("图片集合解析失败");
            } else {
                if (urlList.size() > 1)
                    return R.fail("图片只能上传1张");
                for (String s : urlList) {
                    if (StringUtils.isBlank(s))
                        return R.fail("图片地址为空");
                }
            }
        }

        long l = subjectLessonIssueService.todayIssueCnt(storeUid, staffUid);
        if (l >= 10)
            return R.fail("今日建议反馈已达到上限10次");

        SubjectLessonDto lesson = subjectLessonService.dtoRelationByUid(lessonUid);
        if (lesson == null)
            return R.fail("课次不存在");

        Subjects mainSubjects = subjectsService.getById(lesson.getSubjectMainId());
        if (mainSubjects == null)
            return R.fail("主学科获取失败");
        if (StringUtils.isBlank(mainSubjects.getSubjectDescribe()))
            return R.fail("主学科标识不能为空");

        SubjectLessonIssue data = new SubjectLessonIssue();
        data.setUid(KitUtil.getUuid());
        data.setCorpUid(corpUid);
        data.setStoreUid(storeUid);
        data.setStoreName(storeName);
        data.setSubjectMainId(lesson.getSubjectMainId());
        data.setSubjectId(lesson.getSubjectId());
        String levelName = "";
        if (CollectionUtils.isNotEmpty(lesson.getSubjectList())) {
            levelName = lesson.getSubjectList().stream().collect(Collectors.joining(" / "));
        }
        data.setLevelName(levelName);
        data.setLessonUid(lessonUid);
        data.setLessonName(lesson.getLessonName());
        data.setIssueContent(issueContent);
        data.setMob(mob);
        data.setStatus(1);
        data.setAddStaffUid(staffUid);
        data.setAddStaffName(staffName);
        subjectLessonIssueService.saveOrUpdate(data);

        // 保存图片
        if (CollectionUtils.isNotEmpty(urlList)) {
            List<SubjectLessonIssueImg> newList = new ArrayList<>();
            for (String s : urlList) {
                SubjectLessonIssueImg img = new SubjectLessonIssueImg();
                img.setIssueUid(data.getUid());
                img.setCorpUid(corpUid);
                img.setStoreUid(storeUid);
                img.setUrl(s);
                newList.add(img);
            }
            subjectLessonIssueImgService.saveOrUpdateBatch(newList);
        }

        // 企业微信获取access_token
        String accessToken = (String) redisService.get(RedisParam.QYWEINXIN_ACCESS_TOKEN);
        if (StringUtils.isBlank(accessToken)) {
            AccessTokenDto dto = QyWeiXinUtil.getAccessToken(corpid, secret);
            if (dto != null) {
                accessToken = dto.getAccess_token();
                int expires_in = dto.getExpires_in();
                // redis缓存accessToken
                redisService.set(RedisParam.QYWEINXIN_ACCESS_TOKEN, accessToken, expires_in);
            }
        }
        // 企业微信发送群聊消息
        String name = StringUtils.isNotBlank(mob) ? staffName + " / " + mob : staffName;
        String timeStr = DateUtil.getNowDatetimeStr();
        QyWeiXinUtil.sendToChat(accessToken, lessonchatid,
                QyWeixinMsg.lessonIssue(serverUrl, data.getUid(), storeName, name, levelName, data.getLessonName(), issueContent, timeStr));

        return R.ok();
    }


    @ApiOperation(value = "上传图片至阿里云oss")
    @PostMapping(value = "/uploadImg")
    public R<Object> uploadImg(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "图片文件") @RequestPart(value = "image") MultipartFile file
    ) {
        boolean m = FileUtil.checkFileSize(file.getSize(), 5, "M");
        if (!m) return R.fail("上传图片大小不能超过5M");

        OSSClientUtil ossClientUtil = new OSSClientUtil();
        ossClientUtil.initOss();

        String todayDir = ossClientUtil.getTodaySplitDir(OSSClientUtil.issueDir);

        String resultUrl = ossClientUtil.uploadImg2Oss(todayDir, file);
        ossClientUtil.destory();
        if (StringUtils.isBlank(resultUrl)) {
            return R.fail("上传图片失败");
        }

        return R.ok(todayDir + resultUrl);
    }


    @ApiOperation(value = "员工获取已处理但未读取的意见集合")
    @PostMapping(value = "/getUnreadIssueList")
    public R<Object> getUnreadIssueList(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName
    ) {
        List<SubjectLessonIssue> list = subjectLessonIssueService.getUnreadIssueNum(storeUid, staffUid);

        if (CollectionUtils.isNotEmpty(list)) {
            // 将员工的已处理但未读取的意见 全部更新为已读取
            boolean b = subjectLessonIssueService.updateReadStatus(storeUid, staffUid);
        }

        return R.ok(list);
    }

}
